import React, { useState } from 'react';
import axios from 'axios';
import { Container, TextField, Button, Typography, List, ListItem, ListItemText } from '@mui/material';

const API_URL = 'http://localhost:3333'; // 后端服务URL

function App() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [note, setNote] = useState('');
  const [notes, setNotes] = useState([]);
  const [loggedIn, setLoggedIn] = useState(false);

  const handleRegister = async () => {
    try {
      const response = await axios.post(`${API_URL}/register`, { username, password });
      console.log('Registration successful:', response.data);
    } catch (error) {
      console.error('Registration failed:', error);
    }
  };

  const handleLogin = async () => {
    try {
      const response = await axios.post(`${API_URL}/login`, { username, password });
      console.log('Login successful:', response.data);
      setLoggedIn(true);
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  const handleAddNote = async () => {
    try {
      const response = await axios.post(`${API_URL}/notes`, { username, text: note });
      console.log('Note added:', response.data);
      setNote('');
    } catch (error) {
      console.error('Failed to add note:', error);
    }
  };

  const handleFetchNotes = async () => {
    try {
      const response = await axios.get(`${API_URL}/notes/${username}`);
      console.log('Notes fetched:', response.data);
      setNotes(response.data);
    } catch (error) {
      console.error('Failed to fetch notes:', error);
    }
  };

  return (
    <Container maxWidth="sm">
      <Typography variant="h4" align="center" gutterBottom>
        一个简单的同步网页demo
      </Typography>
      {!loggedIn ? (
        <div>
          <Typography variant="h5" gutterBottom>
            Register
          </Typography>
          <TextField
            fullWidth
            label="Username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            margin="normal"
          />
          <div style={{ marginTop: '16px' }}></div>
          <Button  variant="contained" color="primary" onClick={handleRegister}>
            注册
          </Button>

          <Button variant="contained" color="secondary" onClick={handleLogin}>
            登录
          </Button>
        </div>
      ) : (
        <div>
          <Typography variant="h5" gutterBottom>
            Welcome, {username}!
          </Typography>
          <Typography variant="h6" gutterBottom>
            添加笔记
          </Typography>
          <TextField
            fullWidth
            label="Note"
            value={note}
            onChange={(e) => setNote(e.target.value)}
            margin="normal"
          />
          <Button variant="contained" color="primary" onClick={handleAddNote}>
            确定添加
          </Button>
          <Button variant="contained" color="secondary" onClick={handleFetchNotes}>
            同步笔记
          </Button>
          <Typography variant="h6" gutterBottom>
            笔记列表
          </Typography>
          <List>
            {notes.map((note, index) => (
              <ListItem key={index}>
                <ListItemText primary={note.text} />
                <div>{new Date(note.createdAt).toLocaleString()}</div>
              </ListItem>
            ))}
            <div style={{ borderBottom: '1px solid #ccc' }}></div>
          </List>
        </div>
      )}
      <div><p>by she</p></div>
    </Container>
    
  );
}

export default App;